import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutterDemo/constants.dart';
import 'package:flutterDemo/utils/sp_utils.dart';

class CookieIntercepter extends Interceptor {
  @override
  void onRequest(
      //取出本地cookie
      RequestOptions options,
      RequestInterceptorHandler handler) async {
    //放到请求头里
    SpUtils.getStringList(Constants.SP_COOKIE_List).then((cookieList) {
      options.headers[HttpHeaders.cookieHeader] = cookieList?.join('; ');
      //继续执行
      handler.next(options);
    });
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if (response.requestOptions.path.contains("user/login")) {
      dynamic list = response.headers[HttpHeaders.setCookieHeader];
      List<String> cookieList = [];
      if (list is List) {
        for (String? cookie in list) {
          cookieList.add(cookie!);
          print("这就是库克${cookie}");
        }
      }
      SpUtils.saveStringList(Constants.SP_COOKIE_List, cookieList);
    }
    super.onResponse(response, handler);
  }
}
